package area

import (
	"Project/global"
	"Project/model/area/response"
	"Project/model/common"
	"Project/model/common/request"
	"Project/model/drugs"
	"Project/model/user"
	"errors"
	"log"
)

type RecordService struct {}

// RecordInfo 获取记录
func (r *RecordService) RecordInfo(userID int64,page request.PageRes)(data response.RecordRep,err error)  {
	//	 根据用户ID获取用户的区县ID
	area,err := r.QueryAreaID(userID)
	if err != nil{
		log.Println("查询失败",err)
		return data,err
	}
	var records []common.DrugRecords

	// 普通查询
	if page.Word == ""{
		//	 没有模糊查询
		records,err = r.QueryWithoutObscure(area.AreaID,page)
	}else{
		//	模糊查询
		records,err = r.QueryWithObscure(area.AreaID,page)
	}

	if len(records) == 0 {
		return data,errors.New("记录不存在")
	}

	// 获取总的数据量
	total,err := r.GetTotal(area.AreaID,page)
	if err != nil {
		return data,err
	}
	// 获取总页数f
	nums := r.GetTotalNums(int64(page.PageNums),total)
	/**
	拿到所有记录后进行数据处理:
		recordsMap 存放每个用户购买的所有药品以及数量,以记录id为key
		recordsDistinctMap 对拿到的记录进行去重,以记录id为key
	复制给最终返回的对象
	*/


//  保存药品和数量的map
	recordsMap := make(map[int64][]response.Drugs)
//  去除重复的map
	recordsDistinctMap := make(map[int64]common.DrugRecords)
	for _,v := range records{
		// 药品对象
		dugs := response.Drugs{
			DrugName: v.DrugName,
			DrugNum: v.DrugNum,
		}
		// 去除重复
		if _,ok  := recordsDistinctMap[v.RecordID]; !ok {
			recordsDistinctMap[v.RecordID] = v
		}
		recordsMap[v.RecordID] = append(recordsMap[v.RecordID],dugs)
	}
	// 初始化结果集
	resList  := make([]response.DrugRecordList,len(recordsMap))
	index := 0
	for k,v := range recordsDistinctMap{
		res := response.DrugRecordList{
			UserName: v.Name,
			Phone: v.Phone,
			Card: v.Card,
			SaleName: v.SaleName,
			Address: v.Address,
			LivingArea: v.LivingArea,
			ReasonUse: v.ReasonUse,
			HighRisk: v.HighRisk,
			Time: v.CreatedAt.Format(global.DateFormat),
			DrugList: recordsMap[k],
		}
		resList[index] = res
		index++
	}
	// 最终结果集
	data.ResList = resList
	data.Num = nums
	data.Total = total
	return data,nil
}

func (r *RecordService) RecordPageInfo(userID int64,page request.PageQeryRes)(data []response.DrugRecordList,err error)  {
	//	 根据用户ID获取用户的区县ID
	area,err := r.QueryAreaID(userID)
	if err != nil{
		log.Println("查询失败",err)
		return data,err
	}
	var records []common.DrugRecords

	// 普通查询
	if page.Word == ""{
		//	 没有模糊查询
		records,err = r.QueryPageWithoutObscure(area.AreaID,page)
	}else{
		//	模糊查询
		records,err = r.QueryPageWithObscure(area.AreaID,page)
	}

	if len(records) == 0 {
		return data,errors.New("记录不存在")
	}

	/**
	拿到所有记录后进行数据处理:
		recordsMap 存放每个用户购买的所有药品以及数量,以记录id为key
		recordsDistinctMap 对拿到的记录进行去重,以记录id为key
	复制给最终返回的对象
	*/

	//  保存药品和数量的map
	recordsMap := make(map[int64][]response.Drugs)
	//  去除重复的map
	recordsDistinctMap := make(map[int64]common.DrugRecords)
	for _,v := range records{
		// 药品对象
		dugs := response.Drugs{
			DrugName: v.DrugName,
			DrugNum: v.DrugNum,
		}
		// 去除重复
		if _,ok  := recordsDistinctMap[v.RecordID]; !ok {
			recordsDistinctMap[v.RecordID] = v
		}
		recordsMap[v.RecordID] = append(recordsMap[v.RecordID],dugs)
	}
	// 初始化结果集
	data  = make([]response.DrugRecordList,len(recordsMap))
	index := 0
	for k,v := range recordsDistinctMap{
		res := response.DrugRecordList{
			UserName: v.Name,
			Phone: v.Phone,
			Card: v.Card,
			SaleName: v.SaleName,
			Address: v.Address,
			LivingArea: v.LivingArea,
			ReasonUse: v.ReasonUse,
			HighRisk: v.HighRisk,
			Time: v.CreatedAt.Format(global.DateFormat),
			DrugList: recordsMap[k],
		}
		data[index] = res
		index++
	}
	return data,nil

}

// QueryWithoutObscure 普通查询
func (r *RecordService) QueryWithoutObscure(areaID int64,page request.PageRes)(records []common.DrugRecords,err error){
	/**
			登记表和中间表进行关联，查询出所有符合要求的记录
	*/
	 err = global.GVA_DB.Table("drugs_record").Select([]string{"drugs_record.record_id","name","phone","card","sale_name","living_area","address","high_risk","reason_use","drug_name","drug_num","drugs_record.created_at"}).
		Joins("inner join drugs_middle on drugs_record.record_id = drugs_middle.record_id").
		 Where("drugs_record.area_id = ?",areaID).
		 Where("drugs_record.created_at BETWEEN ? AND ?",page.Date[0],page.Date[1]).
		 Find(&records).Limit(page.PageNums).Error
	 if err != nil {
		 log.Println("查询失败")
		 return nil,err
	 }
	 return records,nil
}

// QueryWithObscure 模糊查询
func (r *RecordService) QueryWithObscure(areaID int64,page request.PageRes)(records []common.DrugRecords,err error){
	/**
	登记表和中间表进行关联，查询出所有符合要求的记录
	*/
	err = global.GVA_DB.Table("drugs_record").Select([]string{"drugs_record.record_id","name","phone","card","sale_name","living_area","address","high_risk","reason_use","drug_name","drug_num","drugs_record.created_at"}).
		Joins("inner join drugs_middle on drugs_record.record_id = drugs_middle.record_id").
		Where("drugs_record.area_id = ?",areaID).
		Where("concat(name,sale_name,phone,card,address,living_area,high_risk,drug_name,reason_use) like ?","%"+page.Word+"%").
		Find(&records).Limit(page.PageNums).Error


	if err != nil {
		log.Println("查询失败")
		return nil,err
	}
	return records,nil
}

// QueryPageWithObscure 分页模糊查询
func (r *RecordService) QueryPageWithObscure(areaID int64,page request.PageQeryRes)(records []common.DrugRecords,err error){
	/**
	登记表和中间表进行关联，查询出所有符合要求的记录
	*/
	err = global.GVA_DB.Table("drugs_record").Select([]string{"drugs_record.record_id","name","phone","card","sale_name","living_area","address","high_risk","reason_use","drug_name","drug_num","drugs_record.created_at"}).
		Joins("inner join drugs_middle on drugs_record.record_id = drugs_middle.record_id").
		Where("drugs_record.area_id = ?",areaID).
		Where("concat(name,sale_name,phone,card,address,living_area,high_risk,drug_name,reason_use) like ?","%"+page.Word+"%").
		Find(&records).Limit(page.PageNums).Offset((page.Page-1)*page.PageNums).Error


	if err != nil {
		log.Println("查询失败")
		return nil,err
	}
	return records,nil
}

// QueryPageWithoutObscure 普通分页查询
func (r *RecordService) QueryPageWithoutObscure(areaID int64,page request.PageQeryRes)(records []common.DrugRecords,err error){
	/**
	登记表和中间表进行关联，查询出所有符合要求的记录
	*/
	err = global.GVA_DB.Table("drugs_record").Select([]string{"drugs_record.record_id","name","phone","card","sale_name","living_area","address","high_risk","reason_use","drug_name","drug_num","drugs_record.created_at"}).
		Joins("inner join drugs_middle on drugs_record.record_id = drugs_middle.record_id").
		Where("drugs_record.area_id = ?",areaID).
		Where("drugs_record.created_at BETWEEN ? AND ?",page.Date[0],page.Date[1]).
		Find(&records).Limit(page.PageNums).Offset((page.Page-1)*page.PageNums).Error

	if err != nil {
		log.Println("查询失败")
		return nil,err
	}
	return records,nil
}

//QueryAreaID  根据用户ID获取用户在所属于的区县
func (r *RecordService) QueryAreaID(userID int64)(user user.UserArea,err error){
	if err = global.GVA_DB.Select("area_id").Find(&user,"user_id = ?",userID).Error;err != nil {
		log.Println("查询失败",err)
		return user,err
	}
	return user,nil
}

// GetTotal 总数据量
func (r *RecordService) GetTotal(areaID int64,page request.PageRes)(total int64,err error){
	// 普通查询获取记录总数
	if page.Word == ""{
		err = global.GVA_DB.Model(drugs.DrugsRecord{}).Select("count(record_id)").Where("area_id = ?",areaID).
			Where("drugs_record.created_at BETWEEN ? AND ?",page.Date[0],page.Date[1]).
			Count(&total).Error
		if err != nil {
			log.Println("查询失败")
			return
		}
		return
	}

	// 模糊查询返回的总数
	err = global.GVA_DB.Table("drugs_record").Select("count(distinct(drugs_middle.record_id))").
		Joins("inner join drugs_middle on drugs_record.record_id = drugs_middle.record_id").
		Where("drugs_record.area_id = ?",areaID).
		Where("concat(name,sale_name,phone,card,address,living_area,high_risk,drug_name,reason_use) like ?","%"+page.Word+"%").Count(&total).Error
	if err != nil {
		log.Println("查询失败")
		return
	}

	return
}

// GetTotalNums 获取总页数
func (r *RecordService) GetTotalNums(nums,total int64) int64{
	if total % nums != 0 {
		return  total / nums +1
	}
	return total / nums
}